package com.gitee.ywj1352.client.handler;

import com.gitee.ywj1352.common.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author wenjie.yang on 2019/10/23.
 */
public class RpcEncoder<T> extends MessageToByteEncoder {

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        Class generics = getGenerics();
        if (generics.isInstance(msg)){
            byte[] dataBytes = SerializationUtil.serialize(msg);
            int length = dataBytes.length;
            // 包长度
            out.writeInt(length);
            //包数据
            out.writeBytes(dataBytes);
        }
    }


    @SuppressWarnings("all")
    private Class getGenerics() {
        Class clazz = this.getClass();
        //getSuperclass()获得该类的父类
        System.out.println(clazz.getSuperclass());
        //getGenericSuperclass()获得带有泛型的父类
        //Type是 Java 编程语言中所有类型的公共高级接口。它们包括原始类型、参数化类型、数组类型、类型变量和基本类型。
        Type type = clazz.getGenericSuperclass();
        System.out.println(type);
        //ParameterizedType参数化类型，即泛型
        ParameterizedType p = (ParameterizedType) type;
        //getActualTypeArguments获取参数化类型的数组，泛型可能有多个
        Class c = (Class) p.getActualTypeArguments()[0];
        return c;
    }
}
